package com.sunmnet.j2ee.service.powerdb.designer.impl;

import com.sunmnet.j2ee.core.powerdb.designer.Commons;
import com.sunmnet.j2ee.core.pub.QueryFilter;
import com.sunmnet.j2ee.core.pub.sqlloader.SqlLoader;
import com.sunmnet.j2ee.dao.BaseDao;
import com.sunmnet.j2ee.entity.powerdb.designer.Field;
import com.sunmnet.j2ee.service.impl.BaseServiceImpl;
import com.sunmnet.j2ee.service.powerdb.designer.FieldService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 蔡岳衡 on 2016/8/8.
 */
@Service("/powerdb/designer/fieldService")
public class FieldServiceImpl extends BaseServiceImpl<Field, Long> implements FieldService {

    /**
     * log4j2日志
     **/
    private static final Logger LOG = LogManager.getLogger(FieldServiceImpl.class.getName());

    private static final String CLASS_NAME = FieldServiceImpl.class.getName();

    private static final String SQL_UPDATE_FIELD_SORTINDEX =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_UPDATE_FIELD_SORTINDEX");

    private static final String FIND_SQL_FOR_SAVE = "from Field t where upper(t.name)=upper(:name) AND t.entityId = :entityId  AND t.versionId = " + Commons.DEF_VERSION_ID;
    private static final String FIND_SQL_FOR_UPDATE = "from Field t where upper(t.name)=upper(:name) AND t.entityId = :entityId  and t.id!=:id AND t.versionId = " + Commons.DEF_VERSION_ID;


    @Override
    @Resource(name = "/powerdb/designer/fieldDao")
    public void setDao(BaseDao<Field, Long> baseDao) {
        super.dao = baseDao;
    }

    @Override
    public int checkRepeat(Field field) {

        Map params = new HashMap();
        params.put("name", field.getName());
        params.put("entityId", field.getEntityId());

        String sql = FIND_SQL_FOR_SAVE;
        if (field.getId() != null) {
            sql = FIND_SQL_FOR_UPDATE;
            params.put("id", field.getId());
        }

        List list = dao.find(sql, params);
        if (list != null && list.size() > 0) {
            LOG.debug("字段" + field.getName() + "已经存在");
            return 1;
        }
        return 0;
    }

    @Override
    public List<Field> getFields(Long entityId, Long versionId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("entityId", entityId);
        params.put("versionId", versionId);
        String hql = "FROM Field f WHERE f.entityId = :entityId AND f.versionId = :versionId";
        return dao.find(hql, params);
    }

    @Override
    public List<Field> getFieldsByModuleId(Long moduleId, Long versionId) {
        String hql = "FROM Field WHERE moduleId = " + moduleId + " AND versionId = " + versionId;
        return dao.findByHql(hql);
    }

    @Override
    public Map<Long, Long> copyFields(List<Field> list, Map<Long, Long> copyedEntitys, Long versionId, Long newModuleId) {
        Map<Long, Long> copyedFields = new HashMap<>();
        Field tmp = null;
        for (Field fi : list) {
            tmp = clone(fi, versionId, newModuleId, copyedEntitys.get(fi.getEntityId()));
            dao.save(tmp);
            copyedFields.put(fi.getId(), tmp.getId());
        }

        LOG.debug("copyFields: {},{},{},{}, result: {} ", list, copyedEntitys, versionId, newModuleId, copyedFields);

        return copyedFields;
    }

    public Field clone(Field fi, Long versionId, Long newModuleId, Long newEntityId) {
        Field field = new Field();
        field.setVersionId(versionId);
        field.setCreateTime(fi.getCreateTime());
        field.setModifyTime(fi.getModifyTime());
        field.setModuleId(newModuleId);
        field.setProjectId(fi.getProjectId());
        field.setNameCn(fi.getNameCn());
        field.setName(fi.getName());
        field.setType(fi.getType());
        field.setLength(fi.getLength());
        field.setDecimalPoint(fi.getDecimalPoint());
        field.setIsNull(fi.getIsNull());
        field.setIsPmKey(fi.getIsPmKey());
        field.setEntityId(newEntityId);
        field.setAutoIncrement(fi.getAutoIncrement());
        field.setScript(fi.getScript());
        field.setCreateAccountId(fi.getCreateAccountId());
        field.setRemark(fi.getRemark());
        field.setModifyAccountId(fi.getModifyAccountId());
        field.setSortIndex(fi.getSortIndex());
        field.setDomainId(fi.getDomainId());
        return field;
    }

    @Override
    public void saveFieldSort(String ids) throws Exception {
        int i = 1;
        LOG.debug("saveFieldSort: {}", ids);
        Map<String, Object> params = new HashMap<>();
        String[] fieldIds = ids.split(",");
        for (String id : fieldIds) {
            params.put("id", Long.parseLong(id));
            params.put("sortIndex", i++);
            dao.executeSql(SQL_UPDATE_FIELD_SORTINDEX, params);
        }
    }

    @Override
    public List findFields(QueryFilter filter) {
        filter.setSql("FROM Field WHERE 1=1 ORDER BY sortIndex");
        String hql = filter.createSql();
        List result = dao.findByHql(hql);
        LOG.debug("findFields: {}, result: {}", filter, result);
        return result;
    }
}
